<template>
  <div>
    <el-upload
      v-model:file-list="internalFileList"
      action="#"
      list-type="picture-card"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      multiple
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { uploadFile } from '@/api/upload'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'update:uploading'])

const internalFileList = ref([]) // 用于 el-upload 的 v-model
const uploadedFiles = ref([])   // 存储 { url, type, uid }
const uploadingCount = ref(0)   // 正在上传的文件计数器

watch(() => props.modelValue, (newValue) => {
  if (newValue.length === 0) {
    internalFileList.value = []
    uploadedFiles.value = []
  }
})

watch(uploadingCount, (newValue) => {
  emit('update:uploading', newValue > 0)
})

const handleUpload = async ({ file }) => {
  try {
    const response = await uploadFile(file)
    if (response.code === 200) {
      const fileType = file.type.startsWith('image') ? 1 : 2 // 1: image, 2: video
      uploadedFiles.value.push({ url: response.data.url, type: fileType, uid: file.uid })
      
      const fileInList = internalFileList.value.find(f => f.uid === file.uid)
      if(fileInList) {
        fileInList.url = response.data.url
      }

      emit('update:modelValue', uploadedFiles.value)
      ElMessage.success('上传成功')
    } else {
      internalFileList.value = internalFileList.value.filter(f => f.uid !== file.uid)
      ElMessage.error(response.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
    internalFileList.value = internalFileList.value.filter(f => f.uid !== file.uid)
  } finally {
    if (uploadingCount.value > 0) {
      uploadingCount.value--
    }
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isVideo = file.type.startsWith('video/')
  if (!isImage && !isVideo) {
    ElMessage.error('只能上传图片或视频文件!')
    return false
  }
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  uploadingCount.value++
  return true
}

const handleRemove = (file) => {
  uploadedFiles.value = uploadedFiles.value.filter(f => f.uid !== file.uid)
  if (file.status !== 'success' && uploadingCount.value > 0) {
    uploadingCount.value--
  }
  emit('update:modelValue', uploadedFiles.value)
}
</script> 